<?php

namespace Xin\Capsule\Laravel;

use Closure;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Xin\Support\Str;

trait WithSearch
{
    /**
     * 使用搜索器条件搜索字段
     * @param EloquentBuilder|QueryBuilder $builder
     * @param string|array $fields 搜索字段
     * @param mixed $data 搜索数据
     * @param string $prefix 字段前缀标识
     * @return EloquentBuilder|QueryBuilder
     */
    protected function withSearch($builder, $fields, $data = [], string $prefix = '')
    {
        if (is_string($fields)) {
            $fields = explode(',', $fields);
        }

        $likeFields = $this->getConfig('match_like_fields') ?: [];

        foreach ($fields as $key => $field) {
            if ($field instanceof Closure) {
                $field($this, $data[$key] ?? null, $data, $prefix);
            } else {
                // 检测搜索器
                $fieldName = is_numeric($key) ? $field : $key;
                $method = 'search' . Str::studly($fieldName) . 'Attribute';

                if ($builder instanceof EloquentBuilder && method_exists($builder->getModel(), $method)) {
                    $builder->getModel()->$method($this, $data[$field] ?? null, $data, $prefix);
                } elseif (isset($data[$field])) {
                    $builder->where(
						$fieldName,
						in_array($fieldName, $likeFields) ? 'like' : '=',
						in_array($fieldName, $likeFields) ? '%' . $data[$fieldName] . '%' : $data[$fieldName]
                    );
                }
            }
        }

        return $builder;
    }
}
